<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="80%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      style="max-width: 100%"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="脚本名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入脚本名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联需求" prop="requirement_id">
            <el-select
              v-model="formData.requirement_id"
              placeholder="请选择关联需求"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="req in requirements"
                :key="req.id"
                :label="req.title"
                :value="req.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="脚本状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="草稿" value="draft" />
              <el-option label="激活" value="active" />
              <el-option label="停用" value="inactive" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签" prop="tags">
            <el-input
              v-model="formData.tags"
              placeholder="多个标签用逗号分隔"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="脚本描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入脚本描述"
        />
      </el-form-item>
    </el-form>

    <!-- YAML脚本编辑器 -->
    <div class="yaml-editor-section">
      <div class="section-header">
        <h3>YAML脚本内容</h3>
        <div class="editor-toolbar">
          <el-button
            v-if="formData.requirement_id"
            size="small"
            type="primary"
            @click="showGenerateDialog"
          >
            <el-icon><Star /></el-icon>
            基于需求生成
          </el-button>
          <el-button size="small" @click="validateYaml">
            <el-icon><CircleCheck /></el-icon>
            验证脚本
          </el-button>
          <el-button size="small" @click="showYamlHelp">
            <el-icon><QuestionFilled /></el-icon>
            语法帮助
          </el-button>
        </div>
      </div>

      <div class="yaml-editor">
        <el-input
          v-model="formData.yaml_content"
          type="textarea"
          :rows="20"
          placeholder="请输入YAML脚本内容"
          class="yaml-textarea"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          {{ mode === 'create' ? '创建' : '保存' }}
        </el-button>
      </div>
    </template>

    <!-- YAML生成对话框 -->
    <YamlGenerateDialog
      v-model:visible="generateDialogVisible"
      :requirement-id="formData.requirement_id"
      @generated="handleYamlGenerated"
    />

    <!-- YAML语法帮助对话框 -->
    <YamlHelpDialog v-model:visible="helpDialogVisible" />
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Star, CircleCheck, QuestionFilled } from '@element-plus/icons-vue'
import { requirementsApi } from '../../api/requirements'
import { createUiAutomationScript, updateUiAutomationScript, validateYamlScript } from '../../api/uiAutomation'
import YamlGenerateDialog from './YamlGenerateDialog.vue'
import YamlHelpDialog from './YamlHelpDialog.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  script: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'create'
  }
})

const emit = defineEmits(['update:visible', 'saved'])

// 响应式数据
const formRef = ref()
const saving = ref(false)
const requirements = ref([])
const generateDialogVisible = ref(false)
const helpDialogVisible = ref(false)

// 表单数据
const formData = reactive({
  name: '',
  description: '',
  requirement_id: null,
  status: 'draft',
  tags: '',
  yaml_content: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入脚本名称', trigger: 'blur' },
    { min: 2, max: 200, message: '脚本名称长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  yaml_content: [
    { required: true, message: '请输入YAML脚本内容', trigger: 'blur' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const dialogTitle = computed(() => {
  return props.mode === 'create' ? '创建UI自动化脚本' : '编辑UI自动化脚本'
})

// 监听器
watch(() => props.visible, (visible) => {
  if (visible) {
    loadRequirements()
    if (props.script && props.mode === 'edit') {
      // 编辑模式，填充表单数据
      Object.assign(formData, {
        name: props.script.name || '',
        description: props.script.description || '',
        requirement_id: props.script.requirement_id || null,
        status: props.script.status || 'draft',
        tags: props.script.tags || '',
        yaml_content: props.script.yaml_content || ''
      })
    } else {
      // 创建模式，重置表单
      resetForm()
    }
  }
})

// 生命周期
onMounted(() => {
  loadRequirements()
})

// 方法
const loadRequirements = async () => {
  try {
    const response = await requirementsApi.getRequirements({ page: 1, size: 1000 })
    requirements.value = response.items || []
  } catch (error) {
    console.error('加载需求列表失败:', error)
  }
}

const resetForm = () => {
  Object.assign(formData, {
    name: '',
    description: '',
    requirement_id: null,
    status: 'draft',
    tags: '',
    yaml_content: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    saving.value = true
    
    const data = { ...formData }
    
    let response
    if (props.mode === 'create') {
      response = await createUiAutomationScript(data)
    } else {
      response = await updateUiAutomationScript(props.script.id, data)
    }
    
    if (response.success) {
      ElMessage.success(props.mode === 'create' ? '脚本创建成功' : '脚本更新成功')
      emit('saved', response.data)
      handleClose()
    }
  } catch (error) {
    console.error('保存脚本失败:', error)
    ElMessage.error('保存脚本失败')
  } finally {
    saving.value = false
  }
}

const showGenerateDialog = () => {
  if (!formData.requirement_id) {
    ElMessage.warning('请先选择关联需求')
    return
  }
  generateDialogVisible.value = true
}

const handleYamlGenerated = (yamlData) => {
  formData.yaml_content = yamlData.yaml_content
  if (!formData.name) {
    formData.name = yamlData.script_name
  }
  if (!formData.description) {
    formData.description = yamlData.description
  }
  ElMessage.success('YAML脚本生成成功')
}

const validateYaml = async () => {
  if (!formData.yaml_content) {
    ElMessage.warning('请先输入YAML脚本内容')
    return
  }
  
  try {
    const response = await validateYamlScript(formData.yaml_content)
    if (response.success) {
      ElMessage.success('YAML脚本格式验证通过')
    } else {
      ElMessage.error(`YAML脚本格式错误: ${response.message}`)
    }
  } catch (error) {
    console.error('验证YAML失败:', error)
    ElMessage.error('验证YAML失败')
  }
}

const showYamlHelp = () => {
  helpDialogVisible.value = true
}
</script>

<style lang="scss" scoped>
.yaml-editor-section {
  margin-top: 20px;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
    
    .editor-toolbar {
      display: flex;
      gap: 8px;
    }
  }
  
  .yaml-editor {
    .yaml-textarea {
      :deep(.el-textarea__inner) {
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 13px;
        line-height: 1.5;
        background-color: #f8f9fa;
        border: 1px solid #e4e7ed;
        
        &:focus {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}

:deep(.el-dialog) {
  .el-dialog__body {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
  }
}
</style>
